package com.cn.common.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.cn.common.model.Result;
import com.cn.common.utils.exception.ServiceException;
import com.cn.common.utils.file.FileUtil;
import com.cn.common.utils.text.StringUtil;
import com.sun.javafx.binding.StringFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class OssUtil {
    private static final Logger log = LoggerFactory.getLogger(OssUtil.class);
    public static String SPLIT = "/";
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;
    @Value("${aliyun.keyId}")
    private String keyId;
    @Value("${aliyun.keySecret}")
    private String keySecret;
    @Value("${aliyun.oss.file.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.file.urlPrefix}")
    private String urlPrefix;

    public OssUtil() {
    }

    public String upload(String path, InputStream is) {
        OSS oss = this.getOSSClient();

        try {
            oss.putObject(this.bucketName, path, is);
        } catch (Exception var8) {
            log.error(var8.getMessage());
            throw new ServiceException("oss 服务异常");
        } finally {
            if (null != oss) {
                oss.shutdown();
            }

        }

        return path.startsWith(SPLIT) ? this.urlPrefix + path : this.urlPrefix + SPLIT + path;
    }

    public boolean delete(String path) {
        OSS oss = this.getOSSClient();

        boolean var4;
        try {
            path.replace(this.urlPrefix, "");
            if (path.indexOf(SPLIT) == 0) {
                path = path.substring(1);
            }

            oss.deleteObject(this.bucketName, path);
            var4 = true;
        } catch (Exception var8) {
            log.error(var8.getMessage());
            throw new ServiceException("oss 服务异常");
        } finally {
            if (null != oss) {
                oss.shutdown();
            }

        }

        return var4;
    }

    private OSS getOSSClient() {
        OSS oss = (new OSSClientBuilder()).build(this.endpoint, this.keyId, this.keySecret);
        return oss;
    }

    public String download(String path) {
        OSS oss = this.getOSSClient();
        if (StringUtil.isEmpty(path)) {
            return "";
        } else {
            if (path.contains("http")) {
                path = path.replace(this.urlPrefix, "");
            }

            GetObjectRequest request = new GetObjectRequest(this.bucketName, path);
            String tmpPath = System.getProperty("java.io.tmpdir") + System.currentTimeMillis() + "." + FileUtil.getFileType(path);
            oss.getObject(request, new File(tmpPath));
            return tmpPath;
        }
    }

    public Result policy(String dir, String id) {
        String host = StringFormatter.concat(new Object[]{"https://", this.bucketName, ".", this.endpoint}).getValue();
        Map<String, String> respMap = null;
        OSS oss = this.getOSSClient();

        try {
            long expireTime = 300L;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000L;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem("content-length-range", 0L, 1048576000L);
            policyConds.addConditionItem(MatchMode.StartWith, "key", dir);
            String postPolicy = oss.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = oss.calculatePostSignature(postPolicy);
            respMap = new LinkedHashMap();
            respMap.put("OSSAccessKeyId", this.keyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("host", host);
            respMap.put("dir", dir);
            respMap.put("expire", String.valueOf(expireEndTime / 1000L));
            respMap.put("attId", id);
        } catch (Exception var19) {
            log.error(var19.getMessage());
            throw new ServiceException("oss 服务异常");
        } finally {
            if (null != oss) {
                oss.shutdown();
            }

        }

        return Result.success(respMap);
    }

    public String getUrlPrefix() {
        return this.urlPrefix;
    }
}